﻿/*
 * \file $Id: SimpleIniWrapper.h 36585 2014-10-10 03:31:59Z skh $
 * \author skh
 * \brief simple ini wrapper
 */
#ifndef _SIMPLE_INI_WRAPPER_H_
#define _SIMPLE_INI_WRAPPER_H_
#include "SimpleIni.h"
#include <string>
#include <algorithm>
#include <assert.h>

/* 
 * 问题的提出：多线程来操作ini文件，容易产生数据互相覆盖的问题
 * 解决的方案：是不让c++对象来持有CSimpleIniA，每次都来打开文件读取数据或保存数据
 */
static
bool set_value_to_ini(const std::string& file, const std::string& section, const std::string& name, const std::string& value)
{
    if(file.empty() || name.empty()) {
        return false;
    }

    std::string lowerStringSection;
    if (section.empty()) {
        lowerStringSection = "base";
    }
	else {
        lowerStringSection = section;
    }

    std::string lowerStringName = name;

    transform(lowerStringSection.begin(), lowerStringSection.end(),lowerStringSection.begin(), tolower);
    transform(lowerStringName.begin(), lowerStringName.end(),lowerStringName.begin(), tolower);

    CSimpleIniA ini;
    SI_Error r = ini.LoadFile(file.c_str());
    //assert(SI_OK == r);
    //if(SI_OK == r) 
    {
        ini.SetValue(lowerStringSection.c_str(), lowerStringName.c_str(), value.c_str());
        ini.SaveFile(file.c_str());
    }

    return true;
}

static
bool get_value_from_ini(const std::string& file, const std::string& section, const std::string& name, std::string& value, const std::string& deault="")
{
    value.clear();
    if(file.empty() || name.empty()) {
        return false;
    }

    std::string lowerStringSection;
    if (section.empty()) {
        lowerStringSection = "base";
    }
    else {
        lowerStringSection = section;
    }

    std::string lowerStringName = name;

    transform(lowerStringSection.begin(), lowerStringSection.end(),lowerStringSection.begin(), tolower);
    transform(lowerStringName.begin(), lowerStringName.end(),lowerStringName.begin(), tolower);

    CSimpleIniA ini;
    SI_Error r = ini.LoadFile(file.c_str());
    //assert(SI_OK == r);
    if(SI_OK == r) {
        const char* p = ini.GetValue(lowerStringSection.c_str(), lowerStringName.c_str(), deault.c_str());
        size_t len = strlen(p);
        value.append(p,len);
    }
    return true;
}

#endif